<template>
  <div class="bigbox">
    <!-- 页面导航搜索盒子 -->
    <div class="topbox">
      <el-form :model="orgname"  label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="5">
          <el-form-item label="建筑群">
            <!-- <el-select size="small" v-model="orgname.buildingId" @change="changeqiye">
              <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
            </el-select> -->
            <FilterSelect2
                    v-model="orgname.buildingId"
                    :optionlist="qiyelist"
                    @updateModelValue="changeqiye"
                    :valuekey="{ name: 'name', value: 'id' }"
                  ></FilterSelect2>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="用能类型">
            <el-select size="small" v-model="orgname.energyType" clearable filterable style="width: 100%;">
              <el-option v-for="(item,index) in yongnenglist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="分摊方式">
            <el-select size="small" v-model="orgname.type" clearable filterable style="width: 100%;">
              <el-option v-for="(item,index) in fentanlist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="模型名称">
            <el-input size="small" style="width: 100%;" v-model="orgname.name" placeholder="请输入模型名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="text-align: right;">
          <el-form-item>
            <el-button size="small" @click="chongzhi">重 置</el-button>
            <el-button type="primary" size="small" @click="getdatalist()">查 询</el-button>
          </el-form-item>
        </el-col>
        </el-row>
      </el-form>
    </div> 
    <!-- 盒子主体 -->
    <div class="bodybox">
      <div class="top">
        <div>分摊模型</div>
        <div class="butti">
          <span>
            <el-dropdown @command="handleCommand">
            <el-button type="primary" size="small" style="margin-right: 10px;">
              <i class="el-icon-plus"></i>新增
            </el-button>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item v-for="(item,index) in fentanlist" :key="index" :command="item.value" style="padding: 0 10px;" >
                <span >{{ item.text }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          </span>
          <TopTile @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile>
        </div>
      </div>
      <!-- 表格区域 -->
      <div class="table">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
            prop="address"
            label="操作"
            align="center"
            width="150">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i @click="modify(row)" class="el-icon-edit" style="color:#1a90fe ;margin-right: 20px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i @click="delet(row)" class="el-icon-delete" style="color: red;cursor: pointer;"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </TableColumn>
            <!-- 底部分页 -->
            <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="15"
                @current-change="getdatalist"
                :total="+totalCount">
          </el-pagination>
        </div>
      </div>
      <!-- 新增/修改dialog弹窗区域 -->
      <div class="dialog">
        <el-dialog
        :title="form.type=='01'?'固定分摊':form.type=='02'?'平均分摊':form.type=='03'?'面积分摊':form.type=='04'?'用量分摊':'末端分摊'"
        :visible.sync="dialogVisible"
        width="45%">
          <div>
            <!-- <el-divider></el-divider> -->
            <el-form :model="form" :rules="rules" label-position="right" label-width="110px" ref="form">
               <el-row>
                <el-col :span="12">
                  <el-form-item label="所属建筑群" prop="buildingId">
                    <!-- <el-select size="small" v-model="form.buildingId" @change="changejianzhu" style="width: 100%;">
                      <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select> -->
                    <FilterSelect2
                    v-model="form.buildingId"
                    :optionlist="qiyelist"
                    @updateModelValue="changejianzhu"
                    :valuekey="{ name: 'name', value: 'id' }"
                  ></FilterSelect2>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用能类型" prop="energyType">
                    <el-select size="small" v-model="form.energyType" @change="changeleixing" style="width: 100%;">
                      <el-option v-for="(item,index) in yongnenglist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
               </el-row>
               <el-row>
                <el-col :span="12">
                   <el-form-item label="分摊模型名称" prop="name" >
                     <el-input style="width: 100%;" v-model="form.name" placeholder="请输入分摊模型名称" size="small"></el-input>
                   </el-form-item>
                </el-col>
                <el-col :span="12">
                   <el-form-item label="分摊模型编号" prop="code">
                     <el-input style="width: 100%;" v-model="form.code" placeholder="请输入分摊模型编号" size="small"></el-input>
                   </el-form-item>
                </el-col>
               </el-row>
               <el-row>
                <el-col :span="12">
                  <el-form-item label="公共表计" prop="measuringPointId">
                    <el-select size="small" v-model="form.measuringPointId" filterable  style="width: 100%;">
                      <el-option v-for="(item,index) in gonggonglist" :key="index" :label="item.meterName" :value="item.measuringPointId" class="option"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="每月分摊日期" prop="dayOfMonth">
                    <el-input style="width: 100%;" v-model="form.dayOfMonth" placeholder="请输入每月分摊日期" size="small"></el-input>
                  </el-form-item>
                </el-col>
               </el-row>
               <el-row>
                 <el-col :span="24">
                   <el-button @click="addgetyonghu" type="primary" size="small">添加分摊表计</el-button>
                   <el-button @click="mianjijisuan" v-show="form.type=='02'||form.type=='03'" type="primary" size="small">分摊比例计算</el-button>
                </el-col>
               </el-row>
               <div style="margin-top: 10px;">
                <!-- <TableColumn
                  ref="tabledata"
                  :tableData="tableDatas" 
                  :tableConfig="tableConfigs" 
                  issize="medium"> -->
                  <el-table
                  border
                  v-loading="loading"
                  :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                  :data="tableDatas"
                  style="width: 100%"
                  issize="medium">
                  <el-table-column
                    prop="meterName"
                    label="表计名称">
                  </el-table-column>
                  <el-table-column
                    prop="roomName"
                    label="房间名称">
                  </el-table-column>
                  <el-table-column
                    prop="customerName"
                    label="用户名称">
                  </el-table-column>
                  <el-table-column
                   v-if="form.type=='03'"
                    prop="roomArea"
                    align="right"
                    label="分摊面积">
                  </el-table-column>
                  <el-table-column
                  label="分摊比例(%)"
                  v-if="form.type!=='04'"
                  #default="{row}">
                    <template>
                      <el-input v-if="form.type !=='04'" v-model="row.ratio" size="small"></el-input>
                      <span v-else>分摊日计算，可查看分摊报表</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="address"
                      label="操作"
                      align="center"
                      width="70">
                      <template #default="{row}">
                        <i @click="delmeter(row)" class="el-icon-delete" style="color: red;cursor: pointer;"></i>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!-- </TableColumn> -->
               </div>
                  <el-divider ></el-divider>
                  <div style="display: flex;justify-content: space-around;">
                    <div style="text-align: center;">合计(%)</div>
                    <div style="text-align: center;">{{ number }}</div>
                  </div>
                  <el-divider ></el-divider>
            </el-form>
          </div>
        <span slot="footer">
          <el-button size="small" @click="quxiao">取 消</el-button>
          <el-button type="primary" size="small" @click="submit">保存</el-button>
        </span>
      </el-dialog>
      <!-- 新增用户表弹窗 -->
      <el-dialog
          width="40%"
          title="分摊表计增加"
          :visible.sync="innerVisible">
          <div>
            <el-form>
              <el-row>
                <el-col :span="12">
                   <el-form-item label="分摊表计">
                    <el-select v-model="value1" multiple placeholder="请选择" filterable  size="small">
                      <el-option
                       class="option"
                        v-for="item in options"
                        :key="item.value"
                        :label="item.meterName"
                        :value="item.meterId">
                      </el-option>
                    </el-select>
                   </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="一键全选">
                    <el-switch
                        v-model="value"
                        @change="changeswitch"
                        active-color="#13ce66"
                        inactive-color="#ccc">
                      </el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <span slot="footer" >
          <el-button size="small" @click="yonghuqu">取 消</el-button>
          <el-button size="small" type="primary" @click="yonghubao">保存</el-button>
        </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {gettablelistapi,getjilianglistapi,postaddmoxingapi,delmoxingapi,getyonghubiaoapi,putjilianglistapi} from '@/api/prwpaid/shares/sharemodel'
import {getzidianxialaapi} from '@/api/guidelines'
import {getloginlistapi} from '@/api/prwpaid/file-management/Architectural-complex'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
   components: {
    TopTile,
    TableColumn
  },
  data() {
    return {
      loading:false,
      number:0,
      value:false,
      innerVisible:false,
      form:{type:'',buildingId:'',energyType:'',dayOfMonth:'1'},
      dialogVisible:false,
      issize: 'medium',
      orgname:{buildingId:'',energyType:'',type:'',name:''},
      qiyelist: [],
      tableData: [],
      tableDatas: [],
      tableConfig: [
        { label: '序号', type:'index' ,center:'center',width:'100'},
        { label: '建筑群名称', prop: 'buildingName' ,width:'220'},
        { label: '用能类型', prop: 'energyTypeName' },
        { label: '分摊方式', prop: 'typeName' },
        { label: '分摊模型名称', prop: 'name' },
        { label: '公共表名称', prop: 'publicMeterName' },
        { label: '公共表地址', prop: 'publicMeterAddress'},
        { label: '每月分摊日期', prop: 'dayOfMonth' , center: 'center' }
      ],
      pageobj: {
        pageNo: 0,
        pageSize:15
      },
      totalCount: '',
      rules: {
        buildingId: [
        { required: true, message: '请选择建筑群', trigger: 'blur' }
        ],
        energyType: [
        { required: true, message: '请选择用能类型', trigger: 'blur' }
        ],
        name: [
        { required: true, message: '请输入分摊模型名称', trigger: 'blur' }
        ],
        code: [
        { required: true, message: '请输入分摊模型编号', trigger: 'blur' }
        ],
        measuringPointId: [
        { required: true, message: '请选择公共表计', trigger: 'blur' }
        ],
        dayOfMonth: [
        { required: true, message: '请输入每月分摊日期', trigger: 'blur' }
        ],
      },
      yongnenglist: [],
      fentanlist: [],
      measuringPoints: '',
      gonggonglist: [],
      options: [],
      value1:[]
    };
  },

  async mounted() {
    const res = await getloginlistapi()
    this.qiyelist = res.data.list
    const localbuildingId = localStorage.getItem('buildingId')
    const isBuildIdInArray = this.qiyelist.some(item => item.id == localbuildingId);
    if(isBuildIdInArray){
      this.orgname.buildingId=localbuildingId?localbuildingId:''
    }else{
      this.orgname.buildingId= ''
    }

    this.getdatalist() 
    // 获取用能类型
    const yongneng = await getzidianxialaapi({ dictType: 'MBM_ENERGY_TYPE' })
    this.yongnenglist = yongneng.data.list
    // 获取分摊类型
    const fentan = await getzidianxialaapi({ dictType: 'MBM_APPORTIONMENT_TYPE' })
    this.fentanlist = fentan.data.list

  },

  methods: {
    // 企业下拉
    changeqiye(val) {
      localStorage.setItem('buildingId', val)
    },
    // 确认新增/修改
    async submit() {
      await this.$refs.form.validate()
      const array = this.tableDatas.map(ele => {
        return {
          endMeterId: ele.meterId,
          measuringPointId: ele.measuringPointId,
          ratio: ele.ratio,
          roomArea:ele.roomArea
        }
      })
       try {
        this.form.id ? await putjilianglistapi({
        apportionmentModelDetailsList: array,
        ...this.form
      }):
        await postaddmoxingapi({
        apportionmentModelDetailsList: array,
        ...this.form
        })
        this.$message.success(this.form.id?'修改成功':'新增成功')
       } catch (error) {
        
       }
     this.quxiao()
     this.getdatalist()
    },
    // 获取表格数据
    async getdatalist() {
      this.$refs.tabledata.loading=true
      const {data:{totalCount,list}} = await gettablelistapi({
      pageNo: this.pageobj.pageNo - 1,
      pageSize: this.pageobj.pageSize,
      ...this.orgname
      })
      this.totalCount = totalCount
      this.tableData = list
      this.$refs.tabledata.loading=false
    },
    // 获取公共表/用户表
    async getbiaolist(buildingId,energyType,meteringType) {
      const jilian = await getjilianglistapi({ buildingId, energyType, meteringType, measuringPoints: this.measuringPoints })
     this.gonggonglist=jilian.data.list
    },
    // 建筑区下拉
    changejianzhu(val) {
      this.getbiaolist(val,this.form.energyType,'PUBLIC')
    },
    // 用能类型下拉
    changeleixing(val) {
      this.getbiaolist(this.form.buildingId, val,'PUBLIC')
    },
    // 添加分摊表计
    async addgetyonghu() {
      this.innerVisible = true
      const jilian = await getjilianglistapi({
        buildingId: this.form.buildingId, energyType: this.form.energyType,
        meteringType:'USER', measuringPoints: this.measuringPoints
      })
     this.options=jilian.data.list
    },
    // 分摊面积计算
    mianjijisuan() {
      if (this.number) return
      if (this.form.type == '02') {
        this.tableDatas.forEach(ele => {
          this.$set(ele,'ratio',(100/this.tableDatas.length).toFixed(2))
        })
      } else if (this.form.type == '03') {
        this.tableDatas.forEach(item => {
            item.roomArea = parseFloat(item.roomArea);
        });
        let totalArea =this.tableDatas.reduce((acc, cur) => acc + cur.roomArea, 0)
        this.tableDatas.forEach(ele => {
          this.$set(ele,'ratio',((+ele.roomArea / totalArea) * 100).toFixed(2))
        })
      }
      this.tableDatas.forEach(ele => {
        if (ele) {
          this.number=100
        } else {
          this.number=0
        }
      })

    },
    // 用户表弹窗保存
    yonghubao() {
      this.tableDatas = this.options.filter(ele => {
        for (let i = 0; i < this.value1.length; i++) {
          if (ele.meterId == this.value1[i]) {
            return ele
          }
        }
      })
      this.yonghuqu()
      if(this.form.type=='01') this.number=100
    },
    // 用户表全选
    changeswitch(val) {
      if (val) {
        this.options.forEach(ele=>this.value1.push(ele.meterId))
      } else {
        this.value1=[]
      }
    },
    // 用户表弹窗取消
    yonghuqu() {
      this.innerVisible = false
      this.options = []
      this.value1=[]
      this.value=false
    },

   // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      exportexcel('mbm-microservice-biz/mbm/apportionment/model/exportExcel',{...this.orgname},'分摊模型')
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
    },
    // 修改
    async modify(val) {
      this.loading=true
      this.handleCommand(val.type)
      this.form = { ...val }
      this.form.buildingId = val.buildingId.toString()
      this.measuringPoints = val.measuringPointId 
      this.getbiaolist(val.buildingId, val.energyType, 'PUBLIC')
      const res = await getyonghubiaoapi({ modelId: val.id })
      this.tableDatas = res.data.list
      if (this.form.type == '01'||this.tableDatas.length!=='0') this.number = 100
      this.loading=false
    },
    // 删除用户表
    delmeter(val) {
      this.tableDatas=this.tableDatas.filter(ele=>ele.measuringPointId!==val.measuringPointId)
    },
    // 新增
    handleCommand(val) {
      this.form.type=val
      this.dialogVisible = true;
      this.form.buildingId =this.orgname.buildingId?this.orgname.buildingId:this.qiyelist[0].id
      this.form.energyType = this.yongnenglist[0].value
      this.form.dayOfMonth='1'
      this.getbiaolist(this.form.buildingId, this.form.energyType, 'PUBLIC')
    },
    // 删除
    delet(val) {
      this.$confirm('此操作将永久删除该档案, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delmoxingapi({ id: val.id })
          this.$message({
            type: res.code == 200 ? 'success' : 'warning',
              message: res.code == 200 ? '删除成功':res.message
            })

          this.getdatalist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置
    chongzhi() {
      localStorage.removeItem('buildingId');
      this.orgname = { buildingId: '', energyType: '', type: '', name: '' }
      this.getdatalist()
    },
    // 取消
    quxiao() {
      this.$refs.form.resetFields()
      this.form={type:'',buildingId:'',energyType:''}
      this.dialogVisible = false
      this.tableDatas = []
      this.number = 0
      this.measuringPoints=''
    }
  }
};
</script>

<style lang="scss" scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding:20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .top{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .butti{
        display: flex;
      }
    }
    .table{
      height: 90%;
      .fenye{
        text-align: right;
        margin-top: 10px;
      }
    }
  }
}
// ::v-deep .el-col-4{
//   text-align: right;
// }
// ::v-deep .el-row{
//   margin-bottom: 5px;
// }
// ::v-deep .el-divider{
//   margin: 10px 0;
//   background-color: #EBEEF5;
// }
// ::v-deep .el-dialog__footer{
//   text-align: center;
// }
// ::v-deep .el-form-item__error{
//   padding-top: 0;
//   font-size: 10px;
// }
</style>